package com.xsky.common.logic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.xsky.table.impl.TableConfiguration;

public class ReflectTable
{
	public static Map reflectMap = null;
	private static ReflectTable instance;
	public static synchronized ReflectTable getInstance() throws DocumentException, IOException
	{

		if (instance == null)
		{
			instance = new ReflectTable();
			instance.configure();
		}

		return instance;
	}
	private ReflectTable()
	{
		
	}
	public void configure() throws DocumentException, IOException
	{
		this.configure(ReflectTable.class.getResourceAsStream("/config/tableReflect.xml"));
	}
	private String getText(InputStream in) throws IOException
	{
		ByteArrayOutputStream bout = new ByteArrayOutputStream();

		byte[] buffer = new byte[1024];

		int num = in.read(buffer);

		while (num > 0)
		{
			bout.write(buffer, 0, num);
			num = in.read(buffer);
		}
		return new String(bout.toByteArray(), "utf-8");
	}
	private void configure(InputStream in) throws DocumentException, IOException
	{

		if(reflectMap != null)
		{
			reflectMap.clear();
		}
		else
		{
			reflectMap = new HashMap();
		}

		String text = this.getText(in);

		Document doc = DocumentHelper.parseText(text);

		List nodeList = doc.selectNodes("//root/item");
		for(int i = 0 ; i < nodeList.size(); i++)
		{
			Element element = (Element)nodeList.get(i);
			reflectMap.put(element.selectSingleNode("name").getText(),element.selectSingleNode("fullName").getText());
		}
	}
}
